package com.ui.controller;

import com.ui.service.Impl.UserServiceImpl;
import com.wanmei.commons.ResultUtils;
import com.wanmei.pojo.Result;
import com.wanmei.pojo.User;
import com.wanmei.util.MD5;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
public class WebUiLoginController {
    @Autowired
    private UserServiceImpl userService;
    /**
     * 登录
     * @return
     */
    @RequestMapping("loginView")
    public String loginView() {
        return "login";
    }

    /**
     * 登录
     * @param uname
     * @param pwd
     * @param response
     * @return
     */
    @RequestMapping("/dologin")
    @ResponseBody
    public Object doLogin(@RequestParam("uname") String uname, @RequestParam("pwd") String pwd,
                          HttpServletResponse response) {
        pwd = MD5.md5(pwd);
        User user = userService.selectByUserName(uname, pwd, response);
        if (user == null) {
            return ResultUtils.fail("登录失败",null,1);
        }
        return ResultUtils.success("登录成功",user,1);
    }

    // 根据token 查看用户信息
    @RequestMapping("/getToken")
    @ResponseBody
    public Object getUserByToken(String token) {
        User user = userService.getRedisByToken(token);
        if (user == null) {
            return ResultUtils.fail("用户session过期",null,0);
        }
       return ResultUtils.success("登录成功",user,1);
    }

    /**
     * 登录退出
     * @param token
     * @return
     */
    @RequestMapping("/logout")
    public String logout(String token) {
        Result msg = userService.logout(token);
        return "redirect:productlist";
    }
}
